<?php

namespace App\Console\Commands;

use App\Libs\Alimama;
use App\Libs\BLogger;
use App\Models\ConvertUrls;
use App\Models\Product;
use Illuminate\Console\Command;
use DB;

class getQingtaoke extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get-qingtaoke';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '抓取轻淘客商品';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $page = 0;
        while($page < 100) {
            $page ++;
            $url = "http://www.qingtaoke.com/qingsou?yongjin=20&s_type=1&sort=1&f=1&isAli=0&cat=0&is_all_selected=1&page={$page}";
            exec(public_path() . "/getData/track-qingtao.py {$url}", $output, $status);

            if (!empty($output)) {
                $qingtaokeGoodsData = json_decode($output[0]);
                foreach ($qingtaokeGoodsData as $qingTaokeGoods) {
                    $url = trim($qingTaokeGoods->goods_url);
                    $aliData = Alimama::getGoodsBySearchKey(['search_key' => urlencode($url)], 1, 1, 0);
                    if (!empty($aliData) && isset($aliData->data->head->status) && $aliData->data->head->status == 'OK') {
                        $goodsData = $aliData->data->pageList;
                        foreach ($goodsData as $gd) {
                            $updateData = [
                                'tbid' => $gd->auctionId,
                                'goods_name' => strip_tags($gd->title),
                                'taobao_title' => strip_tags($gd->title),
                                'goods_pic' => $gd->pictUrl . '_400x400q90.jpg',
                                'guid_content' => $qingTaokeGoods->guid_content,
                                'quan_fee' => $gd->couponAmount * 100,
                                'sales_price' => (int)$gd->zkPrice * 100,
                                'taoke_price' => $gd->zkPrice * 100 - $gd->couponAmount * 100,
                                'sales' => $gd->biz30day,
                                'commission_rate' => $gd->tkRate,
                                'coupon_end' => strtotime($gd->couponEffectiveEndTime),
                                'class_id' => $gd->rootCatId,
                                'update_time' => date('Y-m-d H:i:s', time()),
                                'tmall' => 0,
                                'sort' => 1,
                                'is_top' => 0,
                                'delete_time' => null
                            ];
                            if(isset($qingTaokeGoods->coupon_url)) {
                                $updateData['coupon_link'] = $qingTaokeGoods->coupon_url;

                                DB::beginTransaction();
                                try {
                                    $productModel = new Product();

                                    $productInfo = \DB::table($productModel->getTable())->where('tbid', $updateData['tbid'])->first();
                                    if ($productInfo) {
                                        $goodsId = $productInfo->id;
                                        if($productInfo->sort > 1){
                                            $updateData['sort'] = $productInfo->sort;
                                        }
                                        \DB::table($productModel->getTable())->where('tbid', $updateData['tbid'])->update($updateData);
                                    } else {
                                        $goodsId = \DB::table($productModel->getTable())->insertGetId($updateData);
                                    }

                                    if($goodsId){
                                        if($productModel->updateEsData($goodsId, $updateData)){
                                            BLogger::getLogger('GET_GOODS')->info("商品--{$gd->auctionId}--更新到es数据成功");
                                        }else{
                                            BLogger::getLogger('GET_GOODS')->info("商品--{$gd->auctionId}--更新到es数据失败");
                                        }
                                    }

                                    $convertUrlModel = new ConvertUrls();
                                    if(\DB::table($convertUrlModel->getTable())->where('tbid', $updateData['tbid'])->delete() === false){
                                        \DB::rollBack();
                                        BLogger::getLogger('GET_GOODS')->info("美木---已转的链接--{$updateData['tbid']}--删除失败");
                                        continue;
                                    }

                                    \DB::commit();
                                    BLogger::getLogger('GET_GOODS')->info("从轻淘客抓取了商品ID:$goodsId");
                                } catch (\Exception $e) {
                                    \DB::rollBack();
                                    BLogger::getLogger('GET_GOODS')->error($e);
                                }
                            }
                        }
                    } else {
                        BLogger::getLogger('GET_GOODS')->error('从阿里妈妈获取商品失败');
                        sleep(rand(5, 30));
                    }
                }
            } else {
                BLogger::getLogger('GET_GOODS')->error('从轻淘客获取商品失败');
                sleep(rand(60, 300));
                $page=0;
            }
        }
    }
}
